package com.jwdf.uda.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.databinding.ActivityMainBinding;
import com.jwdf.uda.event.UserEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.ConfigAction;
import com.jwdf.uda.runtime.PermissionRequest;
import com.jwdf.uda.runtime.RuntimePermission;
import com.jwdf.uda.update.UpdateChecker;
import com.jwdf.uda.update.UpdateVersionCallback;
import com.jwdf.uda.utils.AppBus;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.DisplayUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.ShareUtil;

import java.util.List;

import retrofit2.Response;

public class MainActivity extends AbsActivity {
    private static final int REQ_CHECK_PRIVACY = 100;
    private boolean mIsBackPressed;
    private ActivityMainBinding mDataBinding;
    private CountDownTimer mCountDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mDataBinding.tvSkip.getLayoutParams();
        layoutParams.topMargin = DisplayUtils.getStatusBarHeight(this) + DisplayUtils.dipToPix(this, 10);
        layoutParams.rightMargin = DisplayUtils.dipToPix(this, 10);
        mDataBinding.tvSkip.setLayoutParams(layoutParams);
        ShareUtil.init(this);
        ConfigUtils.checkVer(this);
        EventBusUtil.registerEvent(this);

        UpdateChecker.checkForDialog(this, new UpdateVersionCallback() {
            @Override
            public void onLatestVersion() {
                checkPrivacyPermission();
            }

            @Override
            public void onNext() {
                checkPrivacyPermission();
            }
        });

        AppBus.getInstance().register(this);
        mDataBinding.tvSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDataBinding.tvSkip.setVisibility(View.GONE);
                mCountDownTimer.cancel();
                mCountDownTimer=null;
                doSkip();
            }
        });
    }

    @Override
    protected boolean fullScreenMode() {
        return true;
    }

    @Override
    public boolean isSupportSwipeBack() {
        return false;
    }

    @PermissionRequest(REQ_CHECK_PRIVACY)
    private void checkPrivacyPermission() {
        if (RuntimePermission.hasPermissions(this, Manifest.permission.READ_PHONE_STATE)) {
            ConfigUtils.setRejectPrivacyPermission(this, false);
            getSystemConfig();
        } else {
            RuntimePermission.requestPermissions(this, getString(R.string.app_name), REQ_CHECK_PRIVACY, Manifest.permission.READ_PHONE_STATE);
        }
    }

    private void getSystemConfig() {
        ConfigAction configAction = ConfigAction.newInstance(this);
        onNewRequestCall(configAction.request(new AHttpService.IResCallback<PbBean.PbResSystemGetConfig>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResSystemGetConfig> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (!mIsBackPressed) {
                    if (response != null) {
                        if (HttpHelper.showError(MainActivity.this, resultCode, baseServerInfo, getString(R.string.error_net))) {
                        }
                        PbBean.PbResSystemGetConfig sysConfig = response.body();
                        if (sysConfig != null) {
                            ConfigUtils.setPageLength(MainActivity.this, sysConfig.getPageLength());
                            ConfigUtils.setMiddlePageLength(MainActivity.this, sysConfig.getMiddlePageLength());
                            ConfigUtils.setAboutPage(MainActivity.this, sysConfig.getAboutPage());
                            ConfigUtils.setUserProtocol(MainActivity.this, sysConfig.getUserProtocolPage());
                        }
                    }

                    Glide.with(MainActivity.this).load(ConfigUtils.getApiUrl(MainActivity.this) + "/Uploads/Picture/appstartup.jpg")
                            .fallback(R.drawable.launch_bg).placeholder(R.drawable.launch_bg)
                            .error(R.drawable.launch_bg).listener(new RequestListener<String, GlideDrawable>() {
                        @Override
                        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                            mDataBinding.tvSkip.setVisibility(View.GONE);
                            doSkip();
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                            mDataBinding.tvSkip.setVisibility(View.VISIBLE);
                            startCountDownTimer();
                            return false;
                        }
                    }).into(mDataBinding.ivLaunch);
                }
            }
        }));
    }

    private void doSkip() {
        if (!mIsBackPressed) {
            if (!ConfigUtils.getIsLaunch(MainActivity.this)) {
                startActivity(new Intent(MainActivity.this, LaunchActivity.class));
            } else {
                if (ConfigUtils.isUserLogin(MainActivity.this)) {
                    startNewActivity(DefaultMainActivity.class);
                } else {
                    startNewActivity(MainLoginEntryActivity.class);
                }
            }
        }
        finish();
    }

    private void startCountDownTimer() {
        mCountDownTimer = new CountDownTimer(4000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mDataBinding.tvSkip.setText("跳过 " + millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                mDataBinding.tvSkip.setVisibility(View.GONE);
                doSkip();
            }
        };
        mCountDownTimer.start();
    }

    @Override
    protected void onDestroy() {
        EventBusUtil.unregisterEvent(this);
        AppBus.getInstance().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> params) {
        super.onPermissionsDenied(requestCode, params);
        ConfigUtils.setRejectPrivacyPermission(this, true);
        getSystemConfig();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            FragmentManager manager = getSupportFragmentManager();
            int count = manager.getBackStackEntryCount();
            if (count == 0) {
                mIsBackPressed = true;
                finish();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public void onEventMainThread(UserEvent event) {
        if (UserEvent.EVENT_LOGOUT == event.getEvent()) {
            if (TextUtils.equals(getString(R.string.android_force_update_dialog_btn_cancel), event.getExtra())) {
                finish();
            }
        }
    }
}
